﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using LogikBug.ModularMvc.Attributes;
using LogikBug.ModularMvc.Factories;
using LogikBug.ModularMvc.Locations;
using LogikBug.ModularMvc.Registration;

namespace LogikBug.ModularMvc
{
	public class DirectoryModuleProvider : ModuleProvider
	{
		#region Constructors

		public DirectoryModuleProvider()
			: this(MenuFactoryProvider.DefaultMenuFactory)
		{

		}

		public DirectoryModuleProvider(IMenuFactory menuFactory)
		{
			MenuFactory = menuFactory;
		}

		#endregion

		#region Methods

		protected override void GetModules(ILocation location, IRegistrationContext context)
		{
			context.ThrowIfNull();
			location.ThrowIfNull();

			var modules = new List<IModule>();

			foreach (var item in location)
			{
				var assembly = Assembly.LoadFile(Convert.ToString(item));

				if (assembly == null) { continue; }

				var registerModuleAttributes = assembly.GetAttributes<RegisterModuleAttribute>();

				var currentModules = registerModuleAttributes.GetMvcModules();

				if (!currentModules.HasElements())
				{
					currentModules = assembly.GetMvcModules();
				}

				if (currentModules.Count(m => m != null) < 1) { continue; }

				modules.AddRange(currentModules.Where(m => m != null));
			}

			RegisterModules(modules, context);
		}

		#endregion
	}
}